import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
import vuexPersist from "vuex-persist";
export default new Vuex.Store({
  state: {
    list: [
      {
        title: "电影",
        con: [
          { name: "肖申克的救赎", time: new Date() },
          { name: "怦然心动", time: new Date() },
        ],
      },
      {
        title: "书籍",
        con: [
          { name: "围墙", time: new Date() },
          { name: "三国演绎", time: new Date() },
        ],
      },
      {
        title: "综艺",
        con: [
          { name: "王牌对王牌", time: new Date() },
          { name: "快乐大本营", time: new Date() },
        ],
      },
      {
        title: "体育节目",
        con: [
          { name: "nba", time: new Date() },
          { name: "cna", time: new Date() },
        ],
      },
      {
        title: "游戏",
        con: [
          { name: "王者荣耀", time: new Date() },
          { name: "吃鸡", time: new Date() },
        ],
      },
    ],
  },
  mutations: {
    add(state, obj) {
      let flag = false;
      //判断要添加的内容是否存在
      state.list[obj.active].con.forEach((item) => {
        if (item.name == obj.title) {
          flag = true;
          alert("不能重复添加");
        }
        //一旦相等了证明要添加的内容存在了，flag就变成true
      });

      if (flag == false) {
        state.list[obj.active].con.push({
          name: obj.title,
          time: new Date(),
        });
      }
      //循环结束之后才能知道这个数据存不存在，如果还是false证明不存在，就往里添加
    },

    remove(state, obj) {
      state.list[obj.active].con.splice(obj.index, 1);
    },
    sort(state, obj) {
      state.list[obj.active].con.sort((a, b) => {
        return b.time - a.time;
      });
    },
  },
  actions: {},
  modules: {},
  plugins: [
    new vuexPersist({
      localstorage: window.localStorage,
    }).plugin,
  ],
});
